<!-- src/views/Home.vue  -->
<template>
  <FilterHeader @search="
    (e) => {
      setKeywords(e);
    }
  "></FilterHeader>
  <div class="content" id="teacher_report_management">
    <div class="title">报告库</div>
    <div class="tab_area">
      <div :class="['tab_button', { active: handleType === 0 }]" @click="changeHandleType(0)">
        批改报告
      </div>
      <div :class="['tab_button', { active: handleType === 1 }]" @click="changeHandleType(1)">
        优秀案例
      </div>
    </div>
    <div :class="['classification', { collapse: arrowStatus === 'collapse' }]">
      <div :class="['box', { collapse: arrowStatus === 'collapse' }]">
        <div :class="['item', { selected: condition.category_id === item.id }]" v-for="item in classTypes"
          :key="item.id" @click="changeSelectedClass(item.id)">
          <span>{{ item.name }}</span>
        </div>
      </div>
      <div class="icon" @click="changeArrow">
        展开
        <ArrowDownBold :class="['arrow', { collapse: arrowStatus === 'collapse' }]" style="width: 10px;" />
      </div>
    </div>
    <div :class="[
      'filter_table_container',
      { collapse: arrowStatus === 'collapse' },
    ]">
      <div class="filter_area">
        <div class="condition">
          <el-select v-model="condition.class_id" placeholder="班级" size="default" style="width: 200px;" clearable
            @change="resetParams()">
            <el-option v-for="item in classes" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select @change="resetParams()" v-model="condition.student" placeholder="姓名" size="default" filterable
            style="width: 240px;" clearable>
            <el-option v-for="item in students" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </div>
        <div class="actions">
          <div class="button1" @click="batchDownload()">
            批量下载
          </div>
          <div v-if="condition.type != 1" class="button1" @click="
            () => {
              uploadScoreVisible = true;
            }
          ">
            上传成绩
          </div>
          <div v-if="condition.type != 1" class="button1" @click="
            () => {
              exportScore();
            }
          ">
            导出成绩
          </div>
          <div v-if="condition.type != 1" class="button2" @click="
            () => {
              publishScoreVisible = true;
            }
          ">
            发布成绩
          </div>
        </div>
      </div>
      <div class="table_area">
        <el-table v-if="rerender" :data="tableData" style="width: 100%;" align="center" v-loading="loading" row-key="id"
          key="tableKey" @selection-change="handleSelectionChange">
          <el-table-column fixed type="selection" width="55" /> align="center"
          <el-table-column label="序号" prop="index" width="60">
            <template #default="scope"><span>{{ scope.$index + 1 }}</span></template></el-table-column>
          <el-table-column label="报告名称" show-overflow-tooltip prop="name" align="center" />
          <el-table-column label="班级" show-overflow-tooltip prop="classes.name" width="143" align="center">
            <template #default="scope">
              <span v-if="scope.row.classes.name">{{
                scope.row.classes.name
              }}</span>
              <span v-else>{{ "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学生学号" show-overflow-tooltip prop="user.student_number" align="center">
            <template #default="scope">
              <span v-if="scope.row.user.student_number">{{
                scope.row.user.student_number
              }}</span>
              <span v-else>{{ "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学生姓名" show-overflow-tooltip prop="user.nickname" width="100" align="center" />
          <el-table-column label="提交时间" show-overflow-tooltip prop="createtime" :width="dynamicWidth" align="center">
            <template #default="scope">
              <span v-if="scope.row.createtime">{{
                moment.unix(scope.row.createtime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>
              <span v-else>{{ "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="condition.type != 1" label="成绩" show-overflow-tooltip prop="score" width="100"
            align="center">
            <template #default="scope">
              <span class="table_column_text" v-if="scope.row.score !== null">{{
                scope.row.score
              }}</span>
              <span v-else class="red_text">未批改</span>
            </template>
          </el-table-column>
          <el-table-column v-if="condition.type != 1" label="状态" show-overflow-tooltip prop="status_text" width="120"
            align="center">
            <template #default="scope">
              <span class="table_column_text not_publish" v-if="scope.row.status_text === '未发布'"><span
                  class="dot">.</span><span>未发布</span></span>
              <span v-else class="published"><span class="dot">.</span><span>已发布</span></span>
            </template>
          </el-table-column>
          <el-table-column label="收藏" show-overflow-tooltip prop="collect" width="60" align="center">
            <template #default="scope">
              <img @click="toggleCollect(scope.row.id)" style="cursor: pointer;width: 22px;" src="@/assets/tuxingbiaozhu@2x.png"
                v-if="scope.row.collect" />
              <img @click="toggleCollect(scope.row.id)" style="cursor: pointer;width: 22px;" src="@/assets/gary_star.png" v-else />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center">
            <template #default="scope">
              <el-button :class="['table_view_btn', { green: condition.type == 1 }]" type="text" size="small"
                @click="handleView(scope.$index, scope.row)">
                查看
              </el-button>
              <el-button v-if="condition.type != 1" size="small" class="table_edit_btn" type="text"
                @click="handleEdit(scope.$index, scope.row)">
                批改
              </el-button>
              <el-button size="small" class="table_download_btn" type="text"
                @click="handleDownload(scope.$index, scope.row)">
                下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-else><el-empty description="loading.." v-loading="true" /></div>
        <!-- 分页控件 -->
        <div class="pagination_footer">
          <el-pagination background  v-model:current-page="condition.page" v-model:page-size="condition.limit" :total="total"
            :page-sizes="[1, 10, 20, 50]" layout="total, sizes, prev, pager, next"
            @current-change="handlePageChange" @size-change="handleSizeChange" lang="zh-CN"/>
        </div>
      </div>
    </div>
    <el-dialog destroy-on-close modal-class="global_dialog" v-model="uploadScoreVisible" title="上传成绩" width="531"
      @close="
        uploadScoreVisible = false;
      uploadCbData = null;
      file = null;
      ">
      <!-- 默认插槽，用于内容 -->
      <slot>
        <div>
          <el-upload v-if="uploadScoreVisible" class="upload" :on-exceed="handleExceed" :headers="uploadHeader"
            :on-success="handleSuccess" :on-change="handleOnChange" drag show-file-list="false" action="
https://from-master.jw100.com.cn/api/common/upload" accept=".xlsx, .xls">
            <img src="@/assets/upload_placeholder.png" alt="" width="40" />
            <div class="el-upload__text">
              <span v-if="!file">请上传Excel文档</span><span v-else>{{ file }}</span><br />
              <span class="desc">文档模版在下方可以直接下载后进行参考</span>
            </div>
            <template #tip>
              <a href="https://from-master.jw100.com.cn/import_fromdata.xlsx" download class="tip">表单模板下载</a>
            </template>
          </el-upload>
        </div>
      </slot>
      <!-- 自定义按钮插槽 -->
      <template #footer>
        <slot name="footer">
          <el-button @click="uploadScoreVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUploadScoreConfirm">确认发布</el-button>
        </slot>
      </template>
    </el-dialog>
    <el-dialog destroy-on-close modal-class="global_dialog" v-model="publishScoreVisible" title="成绩发布" width="531"
      @close="handlePublishDialogClose">
      <!-- 默认插槽，用于内容 -->
      <slot>
        <el-form ref="formRef" :rules="rules" :model="form" label-width="auto" style="max-width: 600px;">
          <el-form-item label="选择报告" prop="template_id">
            <el-select v-model="form.template_id" placeholder="请选择发布成绩报告" :loading="selectLoading" filterable remote
              :remote-method="remoteMethod">
              <el-option v-for="item in selectReports" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="class_id" label="选择班级">
            <el-select v-model="form.class_id" placeholder="请选择发布成绩班级">
              <el-option v-for="item in classes" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
      </slot>
      <!-- 自定义按钮插槽 -->
      <template #footer>
        <slot name="footer">
          <el-button @click="publishScoreVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePublishScoreConfirm">确认发布</el-button>
        </slot>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from "moment";
import { ref, watch, onMounted, onDeactivated } from "vue";
import FilterHeader from "@/components/FilterHeader.vue";
import request from "@/request";
import { ElMessage, genFileId } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  console.log("我被移除了");
  // 优化 删除watch
  // 以及组件卸载时调用
});
onMounted(async () => {
  await getCategoryTableList();
  await getClassList();
  await getStudentList();
});
const handleType = ref(0);
const arrowStatus = ref("expand");
// 获取分类列表
const classTypes = ref([]);
// 获取班级信息
const classes = ref([]);
// 获取学生信息
const students = ref([]);
// table数据
const tableData = ref([]);
const selectReports = ref([]);
const total = ref(0);
const loading = ref(false);
const selectLoading = ref(false);
const rerender = ref(true);
const selectedRows = ref([]);
const dynamicWidth = ref("205");
const tableKey = ref(0);
const uploadScoreVisible = ref(false);
const uploadCbData = ref(null);
const publishScoreVisible = ref(false);
const uploadHeader = ref({
  token: localStorage.getItem("token"),
});
const file = ref(null);
const formRef = ref(null);
const form = ref({
  template_id: "",
  class_id: "",
});
const rules = ref({
  template_id: [{ required: true, message: "请选择报告", trigger: "change" }],
  class_id: [{ required: true, message: "请选择班级", trigger: "change" }],
});
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
const getCategoryTableList = async () => {
  const res = await request.get("/api/master/from/category");
  if (res.code == 1) {
    classTypes.value = res.data;
    condition.value.category_id = res.data?.[0].id;
  }
};
const getClassList = async () => {
  const res = await request.get("/api/master/classes/list");
  if (res.code == 1) {
    classes.value = res.data;
  }
};
const getStudentList = async () => {
  const res = await request.get("/api/master/user/list");
  if (res.code == 1) {
    students.value = res.data;
  }
};
const getTableList = async () => {
  loading.value = true;
  try {
    const res = await request.post("/api/master/report/list", condition.value);
    if (res.code == 1) {
      tableData.value = res.rows;
      total.value = res.total;
      tableKey.value++; // 强制重新渲染
      setTimeout(() => {
        rerender.value = true;

        const table = document.querySelector(".el-table__body-wrapper");
        if (table) {
          table.style.width = "100%";
          table.scrollLeft = 0;
        }
      }, 50);
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const condition = ref({
  keywords: "",
  class_id: "",
  user_id: "",
  category_id: "",
  page: 1,
  limit: 10,
  type: 0,
});
const resetParams = () => {
  condition.value.page = 1;
};
const setKeywords = (val) => {
  condition.value.keywords = val;
  resetParams();
};
const changeHandleType = (type) => {
  if (type === condition.value.type) return;
  condition.value.type = handleType.value = type;
  resetParams();
  rerender.value = false;
};
const changeSelectedClass = (value) => {
  condition.value.category_id = value;
  resetParams();
};
const changeArrow = () => {
  arrowStatus.value = arrowStatus.value === "expand" ? "collapse" : "expand";
};
const handlePageChange = (newPage) => {
  condition.value.page = newPage;
};

const handleSizeChange = (newSize) => {
  condition.value.limit = newSize;
  condition.value.page = 1;
  loadData();
};
const updateTableData = () => {
  console.log(condition.value);
  // 根据条件 刷新table、
  getTableList();
};
const exportScore = async () => {
  if (!selectedRows.value?.length) {
    ElMessage({
      type: "error",
      message: "请选择一条数据",
    });
    return;
  }
  // TODO: batch exportexport 导出、批量导出
  const res = await request.post("/api/master/report/export_score", {
    template_id: selectedRows.value[0].template.id,
    // template_id: selectedRows.value[0].id,
    class_id: selectedRows.value[0].classes.id,
  });
  if (res.code == 1) {
    console.log(data);
  }
  console.log(selectedRows.value);
};
const handleView = (index, data) => {
  router.push({
    path: "reportDetail",
    query: {
      templateId: data.template.id,
      reportId: data.id,
      name: data.name,
      mode: "preview"
    },
  });
};
const handleEdit = (index, data) => {
  router.push({
    path: "reportDetail",
    query: {
      reportId: data.id,
      name: data.name,
      templateId: data.template.id,
      isCollect: data.collect,
      mode: "correct", //批改模式 进入编辑器 显示 打分组件
    },
  });
};
// 下载、批量下载
const batchDownload = async (data) => {
  let ids = [];
  if (data) {
    ids = [data.id];
  } else {
    if (!selectedRows.value?.length) {
      ElMessage({
        type: "error",
        message: "请选择一条数据",
      });
      return;
    }
    ids = selectedRows.value.map((data) => data.id);
  }
  let formData = new FormData();
  formData.append("ids", ids.join(","));
  //TODO: del domain
  request.post("/api/master/report/download", formData, 
    { headers: { "Content-Type": "multipart/form-data" } }
  ).then((res) => {
    if (res.code == 1) {
      window.open(res.data);
    } else {
      ElMessage({
        type: "error",
        message: res.msg,
      });
    }
  });
  // window.open(
  //   `https://from-master.jw100.com.cn/api/master/report/download?ids=${ids}`
  // );
};
// 收藏
const toggleCollect = async (id) => {
  loading.value = true;
  try {
    const res = await request.post("/api/master/report/collect", { id });
    if (res.code == 1) {
      ElMessage({
        type: "success",
        message: res.msg,
      });
      updateTableData();
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
const handleDownload = (index, data) => {
  console.log("download", data);
  batchDownload(data);
};
// const handleExceed = (files) => {
//   upload.value.clearFiles()
//   const file = files[0]
//   file.uid = genFileId()
//   upload.value.handleStart(file)
// }
const handleSuccess = async (response, file, fileList) => {
  ElMessage({
    type: "success",
    message: response.msg || "文件上传成功",
  });
  uploadCbData.value = {
    ...uploadCbData.vale,
    ...response.data,
  };
};
const handleUploadScoreConfirm = async () => {
  if (!uploadCbData?.value?.url) {
    ElMessage({
      type: "error",
      message: "请上传Excel文档",
    });
    return;
  }
  const formData = new FormData();
  formData.append('file', uploadCbData.value.url); 
  const res = await request.post("/api/master/report/upload_score", formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
  if (res.code == 1) {
    ElMessage({
      type: "success",
      message: res.msg || "上传成绩发布成功",
    });
    uploadScoreVisible.value = false;
    updateTableData();
  }
  console.log(data);
};
const handleOnChange = (uploadFile, uploadFiles) => {
  file.value = uploadFile.name;
};
const handlePublishScoreConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 提交表单逻辑，例如发请求
      // const template_id =  form.value.template_id,// 实际上是报告id
      // const template_id = selectReports.value.filter(
      //   (data) => data.id === form.value.template_id
      // )?.[0]?.template?.id;

      try {
        const res = await request.post("/api/master/report/publish_score", {
          template_id: form.value.template_id || "todo",
          class_id: form.value.class_id,
        });
        if (res.code == 1) {
          ElMessage({
            type: "success",
            message: res.msg || "成绩发布成功",
          });
          publishScoreVisible.value = false;
        }
        console.log("提交表单数据：", form);
      } catch (error) {
        console.log(error);
      }
    } else {
      return false;
    }
  });
};
const handlePublishDialogClose = () => {
  publishScoreVisible.value = false;
  formRef.value.resetFields();
};
const remoteMethod = async (query) => {
  selectLoading.value = true;
  const res = await request.post("/api/master/report/list", {
    keywords: query || "",
    class_id: "",
    user_id: "",
    category_id: "",
    page: 1,
    limit: 500,
  });
  if (res.code == 1) {
    selectReports.value = res.rows;
  }
  selectLoading.value = false;
};
watch(
  condition,
  (newVal, oldVal) => {
    console.log(newVal.type);
    dynamicWidth.value = newVal.type == 1 ? "auto" : "205";
    updateTableData();
  },
  { deep: true }
);
</script>
<style lang="less" scoped>
.content {
  padding: 40px;
  background: #f7f9fd;
  height: calc(100vh - 80px);

  .title {
    font-family: FZLTDHK--GBK1, FZLTDHK--GBK1;
    font-weight: normal;
    font-size: 20px;
    color: #333333;
    line-height: 24px;
    letter-spacing: 2px;
    text-align: left;
    font-style: normal;
  }

  .tab_area {
    padding-top: 25px;
    padding-bottom: 12px;
    display: flex;
    gap: 20px;

    .tab_button {
      padding: 14px 46px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f3f3f6;
      border-radius: 35px;
      font-family: FZLTHK--GBK1, FZLTHK--GBK1;
      font-weight: normal;
      font-size: 16px;
      color: #333333;
      line-height: 18px;
      letter-spacing: 1px;
      text-align: left;
      font-style: normal;
      cursor: pointer;

      &.active {
        border: 1px solid #2d53f8;
        background: #f0f0ff;
        color: #2d53f8;
      }
    }
  }

  .classification {
    display: flex;
    padding: 22px 0;
    border-bottom: 1px solid #deddf1;
    gap: 20px;
    align-items: center;

    &.collapse {
      align-items: end;
    }

    justify-content: space-between;

    .box {
      display: flex;
      gap: 20px;
      align-items: center;
      width: calc(100% - 100px);
      height: 30px;
      min-height: 30px;
      overflow: hidden;
      flex-wrap: wrap;

      &.collapse {
        height: auto;
      }
    }

    .item {
      cursor: pointer;
      font-family: FZLTHK--GBK1, FZLTHK--GBK1;
      font-weight: normal;
      font-size: 16px;
      color: #666666;
      line-height: 18px;
      letter-spacing: 1px;
      text-align: left;
      transition: all 0.3s ease;
      font-style: normal;
      margin-top: 4px;

      &.selected {
        font-family: FZLTDHK--GBK1, FZLTDHK--GBK1;
        font-weight: bold;
        font-size: 18px;
        color: #2d53f8;
        line-height: 22px;
        letter-spacing: 2px;
        text-align: left;
        font-style: normal;
      }
    }

    .icon {
      cursor: pointer;
      height: 17px;
      font-family: FZLTHK--GBK1, FZLTHK--GBK1;
      font-weight: normal;
      font-size: 14px;
      color: #2d53f8;
      line-height: 17px;
      letter-spacing: 1px;
      text-align: left;
      font-style: normal;
      display: flex;
      gap: 11px;
      align-items: center;

      .arrow {
        transition: 0.1s;

        &.collapse {
          transform: rotate(180deg);
        }
      }
    }
  }

  .filter_table_container {
    // height: calc(100% - 172px);
    overflow: auto;

    &.collapse {
      //   height: 0;
      // transform: translateY(-9999px);
    }

    .filter_area {
      display: flex;
      padding: 20px 0;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;

      .condition {
        display: flex;
        gap: 20px;
        align-items: center;
      }

      .actions {
        display: flex;
        gap: 10px;

        >div {
          cursor: pointer;
          border-radius: 20px;
          white-space: nowrap;
          padding: 10px 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-family: FZLTZHUNHK--GBK1, FZLTZHUNHK--GBK1;
          font-weight: normal;
          font-size: 14px;
          max-width: 130px;
          overflow: hidden;
          text-overflow: ellipsis;
          line-height: 17px;
          text-align: left;
          font-style: normal;
        }

        .button1 {
          color: #2d53f8;
          border: 1px solid #1343f5;
        }

        .button2 {
          background: #2d53f8;
          border: 1px solid #1343f5;
          color: #fff;
        }
      }
    }

    .table_area {
      .pagination_footer {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 20px;
      }

      .table_view_btn,
      .table_download_btn {
        &.green {
          color: #13ab20;
        }

        font-family: FZLTZHUNHK--GBK1,
        FZLTZHUNHK--GBK1;
        font-weight: normal;
        font-size: 16px;
        color: #2b4dff;
        line-height: 18px;
        letter-spacing: 1px;
        font-style: normal;
        margin-left: 0;
      }

      .table_edit_btn {
        font-family: FZLTZHUNHK--GBK1, FZLTZHUNHK--GBK1;
        font-weight: normal;
        font-size: 16px;
        line-height: 18px;
        letter-spacing: 1px;
        font-style: normal;
        color: #ce2403;
        margin-left: 0;
      }

      .red_text {
        font-family: FZLTZHUNHK--GBK1, FZLTZHUNHK--GBK1;
        font-weight: normal;
        font-size: 16px;
        color: #ce2100;
        line-height: 18px;
        letter-spacing: 1px;
        font-style: normal;
      }

      .table_column_text {
        font-family: FZLTZHUNHK--GBK1, FZLTZHUNHK--GBK1;
        font-weight: normal;
        font-size: 16px;
        color: #333333;
        line-height: 18px;
        letter-spacing: 1px;
        font-style: normal;
      }

      .not_publish,
      .published {
        .dot {
          height: 100%;
          display: flex;
          align-items: center;
          transform: translateY(-4px);
        }

        // &::before{
        //     content: '.';
        //     width: 1px;
        //     height: 100%;
        //     top:10px;
        //     transform: translateY(-50%);
        //     position: absolute;
        //     left: -12px;

        // }
        position: relative;
        font-family: FZLTZHUNHK--GBK1,
        FZLTZHUNHK--GBK1;
        font-weight: normal;
        font-size: 16px;
        color: #13ab20;
        line-height: 18px;
        letter-spacing: 1px;
        text-align: left;
        font-style: normal;
        align-items: center;
        display: flex;
        justify-content: center;
        gap: 5px;
      }

      .published {
        color: #d88222;
      }
    }
  }
}
</style>
<style>
#teacher_report_management .td {
  padding: 15px 0;
}

#teacher_report_management .table_area .cell {
  font-family: FZLTZHUNHK--GBK1, FZLTZHUNHK--GBK1;
  font-weight: normal;
  font-size: 16px;
  color: #333333;
  letter-spacing: 1px;
  font-style: normal;
}

#teacher_report_management .table_area th .cell {
  font-family: FZLTZHK--GBK1, FZLTZHK--GBK1;
  font-weight: normal;
  font-size: 16px;
  color: #333333;
  line-height: 19px;
  letter-spacing: 1px;
  font-style: normal;
}

#teacher_report_management .el-checkbox__inner {
  background: rgba(216, 216, 216, 0);
  border-radius: 4px;
  border: 1px solid rgba(151, 151, 151, 0.32);
  width: 22px;
  height: 22px;
}

#teacher_report_management .is-checked .el-checkbox__inner {
  background: #2d53f8;
  border: none;
}

#teacher_report_management .is-indeterminate .el-checkbox__inner {
  background: #2d53f8;
  border: none;
  border-radius: 4px;
  width: 22px;
  height: 22px;
}

#teacher_report_management .is-indeterminate .el-checkbox__inner::before {
  top: 45%;
}

#teacher_report_management .is-checked .el-checkbox__inner::after {
  top: 5px;
  left: 9px;
  transform: rotate(45deg) scale(1.5);
}
</style>
